package v1;

import java.io.BufferedReader;
import java.io.InputStreamReader;

class WiFiManager {

    public boolean connectToWifi(WiFiConfig config) {
        System.out.println("尝试连接WiFi: " + config.ssid);

        try {
            boolean success;

            // 方法1: 使用 nmcli (NetworkManager)
            if (isNetworkManagerAvailable()) {
                success = connectWithNmcli(config);
            }
            // 方法2: 使用 wpa_supplicant
            else if (isWpaSupplicantAvailable()) {
                success = connectWithWpaSupplicant(config);
            }
            // 方法3: 使用系统命令
            else {
                success = connectWithSystemCommands(config);
            }

            if (success) {
                // 验证连接状态
                Thread.sleep(3000);
                return verifyWifiConnection(config.ssid);
            }

            return false;

        } catch (Exception e) {
            System.err.println("连接WiFi时发生错误: " + e.getMessage());
            return false;
        }
    }
    public boolean verifyWifiConnection(String ssid) {
        try {
            Process process = Runtime.getRuntime().exec("iwconfig wlan0");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("ESSID:\"" + ssid + "\"")) {
                    return true;
                }
            }

            // 或者使用 nmcli 检查
            process = Runtime.getRuntime().exec("nmcli connection show --active");
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            while ((line = reader.readLine()) != null) {
                if (line.contains(ssid)) {
                    return true;
                }
            }

            return false;

        } catch (Exception e) {
            System.err.println("验证WiFi连接失败: " + e.getMessage());
            return false;
        }
    }

    private boolean isNetworkManagerAvailable() {
        try {
            Process process = Runtime.getRuntime().exec("which nmcli");
            return process.waitFor() == 0;
        } catch (Exception e) {
            return false;
        }
    }

    private boolean isWpaSupplicantAvailable() {
        try {
            Process process = Runtime.getRuntime().exec("which wpa_supplicant");
            return process.waitFor() == 0;
        } catch (Exception e) {
            return false;
        }
    }

    private boolean connectWithNmcli(WiFiConfig config) {
        try {
            System.out.println("使用 nmcli 连接WiFi...");

            // 先扫描网络
            Process scanProcess = Runtime.getRuntime().exec("nmcli dev wifi rescan");
            scanProcess.waitFor();
            Thread.sleep(2000);

            // 连接网络
            String command;
            if (config.password == null || config.password.isEmpty()) {
                command = String.format("nmcli dev wifi connect \"%s\"", config.ssid);
            } else {
                command = String.format("nmcli dev wifi connect \"%s\" password \"%s\"",
                        config.ssid, config.password);
            }

            System.out.println("执行命令: " + command.replace(config.password, "***"));
            Process connectProcess = Runtime.getRuntime().exec(command);

            // 读取输出
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connectProcess.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            int exitCode = connectProcess.waitFor();
            boolean success = exitCode == 0;

            System.out.println("连接结果: " + (success ? "成功" : "失败"));
            System.out.println("输出: " + output.toString());

            return success;

        } catch (Exception e) {
            System.err.println("nmcli连接失败: " + e.getMessage());
            return false;
        }
    }

    private boolean connectWithWpaSupplicant(WiFiConfig config) {
        try {
            System.out.println("使用 wpa_supplicant 连接WiFi...");

            // 创建 wpa_supplicant 配置
            String wpaConfig = String.format(
                    "network={\n" +
                            "    ssid=\"%s\"\n" +
                            "    psk=\"%s\"\n" +
                            "}\n", config.ssid, config.password);

            // 写入临时配置文件
            ProcessBuilder pb = new ProcessBuilder(
                    "wpa_supplicant", "-i", "wlan0", "-c", "/dev/stdin");
            Process process = pb.start();

            process.getOutputStream().write(wpaConfig.getBytes());
            process.getOutputStream().close();

            // 等待连接
            Thread.sleep(5000);

            // 检查连接状态
            Process statusProcess = Runtime.getRuntime().exec("iwconfig wlan0");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(statusProcess.getInputStream()));

            String line;
            boolean connected = false;
            while ((line = reader.readLine()) != null) {
                if (line.contains("ESSID:\"" + config.ssid + "\"")) {
                    connected = true;
                    break;
                }
            }

            statusProcess.waitFor();
            return connected;

        } catch (Exception e) {
            System.err.println("wpa_supplicant连接失败: " + e.getMessage());
            return false;
        }
    }

    private boolean connectWithSystemCommands(WiFiConfig config) {
        try {
            System.out.println("使用系统命令连接WiFi...");

            // 尝试使用 ifconfig 和 iwconfig
            String[] commands = {
                    "ifconfig wlan0 up",
                    String.format("iwconfig wlan0 essid \"%s\"", config.ssid),
                    "dhclient wlan0"
            };

            for (String command : commands) {
                System.out.println("执行: " + command);
                Process process = Runtime.getRuntime().exec(command);
                int exitCode = process.waitFor();

                if (exitCode != 0) {
                    System.err.println("命令执行失败: " + command);
                    return false;
                }
                Thread.sleep(1000);
            }

            // 验证连接
            Process checkProcess = Runtime.getRuntime().exec("iwconfig wlan0");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(checkProcess.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("ESSID:\"" + config.ssid + "\"")) {
                    return true;
                }
            }

            return false;

        } catch (Exception e) {
            System.err.println("系统命令连接失败: " + e.getMessage());
            return false;
        }
    }

    public String getCurrentWifiStatus() {
        try {
            Process process = Runtime.getRuntime().exec("iwconfig wlan0");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            StringBuilder status = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                status.append(line).append("\n");
            }

            process.waitFor();
            return status.toString();

        } catch (Exception e) {
            return "无法获取WiFi状态: " + e.getMessage();
        }
    }
}